//src/user/auth/auth.guard.ts
import { CanActivate, ExecutionContext, Injectable ,UnauthorizedException} from "@nestjs/common";
import {AuthService} from "./auth.service";
import { Request } from "express";
@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private readonly authService: AuthService) { }
  
  async canActivate(context: ExecutionContext): Promise<boolean> {
  const request = context.switchToHttp().getRequest<Request>();
  const token = this.authService.extractToken(request);
  
  if (!token) {
      throw new UnauthorizedException('缺少访问令牌');
  }
  
  const user = await this.authService.validateUser(token);
  if (!user) {
      throw new UnauthorizedException('无效的用户标识');
  }
  
  // 确保 user 对象包含 id 属性
  request.user = { id: user.id, username: user.username };
  return true;
}
}